package com.globalwave.system.web;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import com.globalwave.base.BaseAction;
import com.globalwave.common.exception.BusinessException;
import com.globalwave.system.entity.SessionUser;
import com.globalwave.system.web.annotations.Pid;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class PrivilegeCheckInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = -4519855194951398071L;
    
    Log log = LogFactoryImpl.getLog(this.getClass()) ;
    
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {

    	if (log.isDebugEnabled()) {
            log.debug("action class : " + actionInvocation.getProxy().getAction().getClass().getName()) ;
            log.debug("action method : " + actionInvocation.getProxy().getMethod()) ;
    	}
    	
        final BaseAction action = (BaseAction) actionInvocation.getProxy().getAction() ;
        final String methodName = actionInvocation.getProxy().getMethod() ;
        final Method method = action.getClass().getMethod(methodName, new Class[]{}) ;
        
        final Pid pid = method.getAnnotation(Pid.class) ;
        if(pid == null || pid.ignore() || pid.value() == Pid.DO_NOT_CHECK) {
            return actionInvocation.invoke() ;
        }
        
        final SessionUser user = 
            (SessionUser) action.getRequest().getSession().getAttribute(SessionUser.SESSION_PK) ;
        
        if (user == null) {
            //action.renderXML(action.getMessage(null, action.getText("error.user.notexist")).asXML()) ;
            //return null ;
        	throw new BusinessException("1000") ;// 未登陆或已经超时，请重新登陆！
        }
        
        SessionUser.set(user) ;
        
        if(user.hasPrivilege(pid.value())) {
            return actionInvocation.invoke() ;
        } else {
            //action.renderXML(action.getMessage(null, action.getText("error.user.notexist")).asXML()) ;
            //return null ;
        	throw new BusinessException("1001") ;// 当前用户没有操作权限！
        }
    }

}
